package com.applozic.mobicomkit.uiwidgets.conversation.fragment;

import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.applozic.mobicomkit.api.conversation.Message;
import com.applozic.mobicomkit.api.conversation.MessageIntentService;
import com.applozic.mobicomkit.api.conversation.MobiComConversationService;
import com.applozic.mobicomkit.api.conversation.SyncCallService;
import com.applozic.mobicomkit.channel.service.ChannelService;
import com.applozic.mobicomkit.uiwidgets.conversation.MultimediaOptionsGridView;
import com.applozic.mobicomkit.uiwidgets.conversation.activity.ConversationActivity;
import com.applozic.mobicomkit.uiwidgets.conversation.adapter.MobicomMultimediaPopupAdapter;
import com.applozic.mobicommons.commons.core.utils.LocationInfo;
import com.applozic.mobicommons.commons.core.utils.Utils;
import com.applozic.mobicommons.json.GsonUtils;
import com.applozic.mobicommons.people.SearchListFragment;
import com.applozic.mobicommons.people.channel.Channel;
import com.applozic.mobicommons.people.contact.Contact;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetRoomUsersRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetRoomUsersResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;


public class ConversationFragment extends MobiComConversationFragment implements SearchListFragment {

    public static final int ATTCHMENT_OPTIONS = 6;
    private static final String TAG = "ConversationFragment";
    private final static String CONTACT = "CONTACT";
    private final static String CHANNEL = "CHANNEL";
    private final static String CONVERSATION_ID = "CONVERSATION_ID";
    private final static String SEARCH_STRING = "SEARCH_STRING";
    InputMethodManager inputMethodManager;
    private MultimediaOptionsGridView popupGrid;
    private int roomCount;
    private MobicomMultimediaPopupAdapter mobicomMultimediaPopupAdapter;
    private View rootView;

    public static ConversationFragment newInstance(Contact contact, Channel channel, Integer conversationId, String searchString) {
        ConversationFragment f = new ConversationFragment();
        Bundle args = new Bundle();
        if (contact != null) {
            args.putSerializable(CONTACT, contact);
        }
        if (channel != null) {
            args.putSerializable(CHANNEL, channel);
        }
        if (conversationId != null) {
            args.putInt(CONVERSATION_ID, conversationId);
        }
        args.putString(SEARCH_STRING, searchString);
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
    }

    private void initChat() {
        this.messageIntentClass = MessageIntentService.class;
        this.conversationService = new MobiComConversationService(getActivity());
        hideExtendedSendingOptionLayout = true;
    }

    private void initData() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            contact = (Contact) bundle.getSerializable(CONTACT);
            channel = (Channel) bundle.getSerializable(CHANNEL);
            currentConversationId = bundle.getInt(CONVERSATION_ID);
            searchString = bundle.getString(SEARCH_STRING);
            if (contact != null) {
                contact.setUnreadCount(0);
                appContactService.updateContact(contact);
            }
            if (searchString != null) {
                SyncCallService.refreshView = true;
            }
        }
    }

    public void attachLocation(Location mCurrentLocation) {

        if (mCurrentLocation != null) {
            LocationInfo info = new LocationInfo(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
            String locationInfo = GsonUtils.getJsonFromObject(info, LocationInfo.class);
            sendMessage(locationInfo, Message.ContentType.LOCATION.getValue(), null);
        } else {
            if (getActivity() != null) {
                utils.Utils.showToast(Common.NO_LOCATION);
            }
        }
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        initChat();
        rootView = super.onCreateView(inflater, container, savedInstanceState);
        initView();

        getRoomInfo();
        return rootView;
    }

    /**
     * 初始化话View
     */
    private void initView() {
        initMultimediaView();
        if (alCustomizationSettings.isHideAttachmentButton()) {

            myAttachButton.setVisibility(View.GONE);
            myMessageEditText.setPadding(20, 0, 0, 0);
        }
//        sendType.setSelection(1);

        myMessageEditText.setHint(com.applozic.mobicomkit.uiwidgets.R.string.enter_message_hint);

        multimediaPopupGrid.setVisibility(View.GONE);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
                com.applozic.mobicomkit.uiwidgets.R.array.secret_message_timer_array, com.applozic.mobicomkit.uiwidgets.R.layout.mobiframework_custom_spinner);

        adapter.setDropDownViewResource(com.applozic.mobicomkit.uiwidgets.R.layout.mobiframework_custom_spinner);

        inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);

        myMessageEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                multimediaPopupGrid.setVisibility(View.GONE);
                emoticonsFrameLayout.setVisibility(View.GONE);
            }
        });


        myAttachButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_chat_plus_feature_toggle");
                if (contact != null && !contact.isBlocked() || channel != null) {
                    if (attachmentLayout.getVisibility() == View.VISIBLE) {
                        Toast.makeText(getActivity(), com.applozic.mobicomkit.uiwidgets.R.string.select_file_count_limit, Toast.LENGTH_LONG).show();
                        return;
                    }
                }

                if (channel != null) {
                    if (Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType())) {
                        String userId = ChannelService.getInstance(getActivity()).getGroupOfTwoReceiverUserId(channel.getKey());
                        if (!TextUtils.isEmpty(userId)) {
                            Contact withUserContact = appContactService.getContactById(userId);
                            if (withUserContact.isBlocked()) {
                                userBlockDialog(false, withUserContact, true);
                            } else {
                                processAttachButtonClick(view);
                            }
                        }
                    } else {
                        processAttachButtonClick(view);
                    }
                } else if (contact != null) {
                    if (contact.isBlocked()) {
                        userBlockDialog(false, contact, false);
                    } else {
                        processAttachButtonClick(view);
                    }
                }
            }
        });

    }

    @Override
    protected void processMobiTexterUserCheck() {

    }

    public void updateTitle() {
        super.updateTitle();
    }

    public void hideMultimediaOptionGrid() {
        if (multimediaPopupGrid.getVisibility() == View.VISIBLE) {
            multimediaPopupGrid.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        if (TextUtils.isEmpty(newText)) {
            conversationAdapter.getFilter().filter(null);
        } else {
            conversationAdapter.getFilter().filter(newText);
        }
        return true;
    }

    /**
     * 显示底部menu
     *
     * @param view
     */
    void processAttachButtonClick(View view) {
        multimediaPopupGrid.setVisibility(View.VISIBLE);
        emoticonsFrameLayout.setVisibility(View.GONE);

        if (inputMethodManager.isActive()) {
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }

    }

    /**
     * 初始化底部附加gridView
     */
    private void initMultimediaView() {
        mobicomMultimediaPopupAdapter = new MobicomMultimediaPopupAdapter(getActivity());
        multimediaPopupGrid.setAdapter(mobicomMultimediaPopupAdapter);
        multimediaPopupGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                MobicomMultimediaPopupAdapter.MobicomMultimediaModel mobicomMultimediaModel = mobicomMultimediaPopupAdapter.getList().get(i);
                if (mobicomMultimediaModel != null) {
                    switch (mobicomMultimediaModel.getType()) {
                        case MobicomMultimediaPopupAdapter.MobicomMultimediaModel.TYPE_CAMARI:
                            ((ConversationActivity) getActivity()).isTakePhoto(true);
                            ((ConversationActivity) getActivity()).processCameraAction();
                            break;
                        case MobicomMultimediaPopupAdapter.MobicomMultimediaModel.TYPE_PHOTO:
                            ((ConversationActivity) getActivity()).isAttachment(true);
                            ((ConversationActivity) getActivity()).startAlbum();
                            break;
                        case MobicomMultimediaPopupAdapter.MobicomMultimediaModel.TYPE_RED_PACKET:
                            ((ConversationActivity) getActivity()).startRedPacketActivity();

                            break;
                    }
                }
            }
        });
    }

    public void reload() {

        try {
            StringBuffer stringBufferTitle = new StringBuffer();
            if (contact != null) {
                Contact updatedInfoContact = appContactService.getContactById(contact.getContactIds());
                if (updatedInfoContact.isDeleted()) {
                    Utils.toggleSoftKeyBoard(getActivity(), true);
//                    userNotAbleToChatLayout.setVisibility(View.VISIBLE);
                    individualMessageSendLayout.setVisibility(View.GONE);
                }
                if (updatedInfoContact != null && (!TextUtils.isEmpty(contact.getDisplayName())) && (!contact.getDisplayName().equals(updatedInfoContact.getDisplayName()))) {
                    stringBufferTitle.append(updatedInfoContact.getDisplayName());
                }
            } else if (channel != null) {
                if (Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType())) {
                    String userId = ChannelService.getInstance(getActivity()).getGroupOfTwoReceiverUserId(channel.getKey());
                    if (!TextUtils.isEmpty(userId)) {
                        Contact withUserContact = appContactService.getContactById(userId);
                        if (withUserContact != null && (!TextUtils.isEmpty(contact.getDisplayName())) && (!contact.getDisplayName().equals(withUserContact.getDisplayName()))) {
                            stringBufferTitle.append(withUserContact.getDisplayName());
                        }
                    }
                }
            }
            if (!TextUtils.isEmpty(stringBufferTitle)) {
                if (stringBufferTitle.toString() != null && !stringBufferTitle.toString().equals("null")) {
                    boolean isSingle = getActivity().getIntent().getBooleanExtra("is_single", false);
                    if (!isSingle && roomCount != 0) {
                        ((TextView) (getActivity()).findViewById(com.lottery.ruok.lottrey.R.id.group_name)).setText(stringBufferTitle + "(" + roomCount + ")");
                    } else {
                        ((TextView) (getActivity()).findViewById(com.lottery.ruok.lottrey.R.id.group_name)).setText(stringBufferTitle);
                    }
                } else {
                }
            }
            conversationAdapter.refreshContactData();
            conversationAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void getRoomInfo() {
        RetrofitBase.getRetrofit().create(GetRoomUsersRequest.class)
                .getResult(UserInfo.getToken(), UserInfo.getRoomId() , null, 10, 0)
                .compose(RxHelper.<GetRoomUsersResponse>handleResult())
                .subscribeWith(new RxSubscribe<GetRoomUsersResponse>(getActivity()) {
                    @Override
                    protected void _onNext(GetRoomUsersResponse getRoomUsersResponses) {
                        roomCount = getRoomUsersResponses.getCount();
                        updateTitle();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }
}